package com.sunny.netty.handler;

import com.sunny.netty.constants.EchoConstants;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * 固定长度解析器服务端
 *
 * @author sunny
 * @date 2018/12/10
 */
public class FixedLengthFrameDecoderServerHandler extends ChannelInitializer {
    @Override
    protected void initChannel(Channel channel) throws Exception {
        channel.pipeline().addLast(new FixedLengthFrameDecoder(EchoConstants.FRAME_LENGTH))
                .addLast(new StringDecoder())
                .addLast(new FixedLengthServerHandler());
    }

    private class FixedLengthServerHandler extends ChannelHandlerAdapter {

        private int counter;

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ctx.close();
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            String message = (String) msg;
            System.out.println("FixedLengthServer 接收到的消息 :" + message + "; 当前统计:" + ++counter);
        }
    }

    public static void bind(int port) {
        //处理网络事件的一组NIO线程组
        NioEventLoopGroup masterGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(masterGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                .handler(new LoggingHandler(LogLevel.DEBUG))
                .childHandler(new FixedLengthFrameDecoderServerHandler());

        try {
            //绑定端口，同步等待成功
            System.out.println("绑定端口，同步等待成功。。。");
            ChannelFuture future = bootstrap.bind(port);
            //等待服务器监听端口关闭
            future.channel().closeFuture().sync();
            System.out.println("等待服务器监听端口关闭。。。");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            masterGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            System.out.println("优雅释放线程池。。。。");
        }
    }

    public static void main(String[] args) {
        bind(4040);
    }
}
